package com.learn.grpc.loadbalance;

import cn.hutool.core.thread.ThreadUtil;
import com.learn.grpc.grpc.LbServiceGrpc;
import com.learn.grpc.hello.PingRequest;
import com.learn.grpc.hello.PingResponse;
import io.grpc.LoadBalancerRegistry;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.NameResolverRegistry;
import org.junit.Test;

public class LbClient {

    @Test
    public void loadBalanceTest() {

        // 注册命名服务解析器
        NameResolverRegistry.getDefaultRegistry().register(new LbNameProvider());
        // 注册负载策略
        LoadBalancerRegistry.getDefaultRegistry().register(new LbLoadBalancerProvider());

        //1.构建网络通道
        ManagedChannel managedChannel = ManagedChannelBuilder
                .forTarget("lb://rpc-server")
                .defaultLoadBalancingPolicy("custom_round_robin")  // 自定义负载策略
                .usePlaintext()
                .build();

        //2.构建客户端
        LbServiceGrpc.LbServiceBlockingStub stub = LbServiceGrpc.newBlockingStub(managedChannel);

        //3.发送多次请求
        for (int i = 0; i < 100; i++) {
            PingRequest request = PingRequest.newBuilder()
                    .setContent("zhangsan_" + i)
                    .build();
            PingResponse resp = stub.ping(request);
            ThreadUtil.sleep(1000);

            System.out.println(String.format("code:%s, message:%s, data:%s", resp.getCode(), resp.getMessage(), resp.getData()));
        }
    }


}
